package com.itheima.reggie.web.controller;

import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.SmsTemplate;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

//点餐端用户登录表现层控制器
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private HttpSession session;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    //点餐端获取验证码
    @PostMapping("/sendMsg")
    public ResultInfo login(@RequestBody Map<String, String> map) {
        //获取传过来的电话号
        String phone = map.get("phone");
        //登陆所需要的验证码
        String code = "123";
        //将验证码存到会话域中
        //session.setAttribute(Constant.USER_PHONE_CODE, code);

        //改:将验证码存到Redis缓存服务器中
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set(Constant.USER_PHONE_CODE + phone, code, 5, TimeUnit.MINUTES);//存5分钟,过期失效

        //返回
        return ResultInfo.success();
    }

    //点餐端登录
    @PostMapping("/login")
    public ResultInfo index(@RequestBody Map<String, String> map) {
        //获取请求参数
        String phone = map.get("phone");
        String code = map.get("code");
        //校验验证码
        //a.从会话域中取出登陆时的验证码
        //String loginCode = (String) session.getAttribute(Constant.USER_PHONE_CODE);

        //改:从Redis缓存服务器中将验证码取出来
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String redisCode = (String) valueOperations.get(Constant.USER_PHONE_CODE + phone);

        //b.比较两次的验证码
        if (code == null || redisCode == null || !redisCode.equals(code)) {
            throw new CustomException("验证码输入错误,请重新输入!");
        }
        //验证码输入正确了,再根据手机号查询是否注册过
        User user = userService.findByPhone(phone);
        //没注册过
        if (user == null) {
            //手机号没注册过
            user = new User();
            //将登陆的手机号设置进对象中
            user.setPhone(phone);
            //将对象保存到数据库中
            userService.save(user);
        }
        //注册了
        if (user != null) {
            //将登录信息存入会话域中
            session.setAttribute(Constant.SESSION_USER, user);
        }
        return ResultInfo.success();
    }

    //点餐端退出登录
    @PostMapping("/logout")
    public ResultInfo logout() {
        //清除登录信息
        session.removeAttribute(Constant.SESSION_USER);
        //返回
        return ResultInfo.success();
    }
}
